package com.luhuiguo.cms.client.presenter;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.luhuiguo.cms.shared.event.LoadArticlesEvent;
import com.luhuiguo.cms.shared.event.LoadArticlesEventHandler;
import com.luhuiguo.cms.shared.model.ArticleListModel;
import com.luhuiguo.cms.shared.model.ChannelTreeModel;
import com.luhuiguo.cms.shared.rpc.LoadArticles;
import com.luhuiguo.cms.shared.rpc.LoadArticlesResult;
import com.luhuiguo.gwt.dispatcher.client.DispatcherAsync;
import com.luhuiguo.gwt.presenter.client.EventBus;

public class ArticleProxy extends RpcProxy<PagingLoadResult<ArticleListModel>> {

    @SuppressWarnings("unused")
    private EventBus eventBus;

    private DispatcherAsync dispatcher;

    private ChannelTreeModel channelTreeModel;

    @Inject
    public ArticleProxy(EventBus eventBus, DispatcherAsync dispatcher) {
        this.eventBus = eventBus;
        this.dispatcher = dispatcher;

        eventBus.addHandler(LoadArticlesEvent.TYPE, new LoadArticlesEventHandler() {

            public void onLoadArticles(LoadArticlesEvent event) {
                channelTreeModel = event.getChannelTreeModel();
            }
        });

    }

    @Override
    protected void load(final Object loadConfig, final AsyncCallback<PagingLoadResult<ArticleListModel>> callback) {
        PagingLoadConfig cfg = (PagingLoadConfig) loadConfig;

        dispatcher.execute(new LoadArticles(channelTreeModel.getType(), channelTreeModel.getId(), cfg.getOffset(), cfg
                .getLimit()), new AsyncCallback<LoadArticlesResult>() {

            @Override
            public void onFailure(Throwable caught) {
                callback.onFailure(caught);

            }

            @Override
            public void onSuccess(LoadArticlesResult result) {

                callback.onSuccess(new BasePagingLoadResult<ArticleListModel>(result.getArticles(), result.getStart(),
                        result.getTotalCount()));

            }
        });

    }
}
